<?php
/**
 * Copyright (c) 2010, Slawomir Mazur <mazursllawek@gmail.com>
 * 
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions 
 * are met:
 * 
 * o Redistributions of source code must retain the above copyright notice, 
 *   this list of conditions and the following disclaimer.
 * o Redistributions in binary form must reproduce the above copyright notice,
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 * o Neither the name of the Softisland nor the names of its contributors
 *   may be used to endorse or promote products derived from this software
 *   without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
 * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
/**
 * Enter description here...
 *
 * @package     System
 * @copyright   Slawomir Mazur (c) 2010 (http://www.zend.com/zce.php?c=ZEND011643)
 * @license     http://www.opensource.org/licenses/bsd-license.php
 * @author      Slawomir Mazur <mazursllawek@gmail.com>
 */

class System_Model_Attribute extends Zend_Db_Table_Abstract
{
	const ATTRIBUTE_NAMES_AS_ARRAY = 'ATTRIBUTE_NAMES_AS_ARRAY';
	
	const CODE_ON_ATTRIBUTES_MAPPING = 'CODE_ON_ATTRIBUTES_MAPPING';
	
	const ATTRIBUTES_MAPPING = 'ATTRIBUTES_MAPPING';
	
	const CACHE_TAGS = 'ATTRIBUTES';
	
	protected $_name = 'attribute';
	
	protected $_primary = 'attribute_id';
	
	protected $_collection = null;
	
	const SEARCHABLE = 1;
	
	public function getCollection()
	{
		$select = $this->select()->order('name');
		
		return $this->fetchAll($select);
	}
	
	public function checkWhetherAttributeTableExists($table)
	{
		$tableName = trim((string) $table);
		
		if (empty($tableName)) {
			throw new Exception('Empty table name given');
		}
		
		$exists = Gp_App::getModel('system/table')
			->tableExists($tableName);
			
		return $exists;
	}
	
	public function checkWhetherAttributeColumnExists($column)
	{
		$columnName = trim((string) $column);
		
		if (empty($columnName)) {
			throw new Exception('Empty column name given');
		}
		
		$exists = Gp_App::getModel('system/table')
			->columnExists($columnName);
			
		return $exists;
	}
	
	public function getAttributesCount()
	{
		$select = $this->select()
				->from($this->_name, array('count' => 'COUNT(*)'));
		
		return $this->fetchRow($select);
	}
	
	public function getSearchableAttributes()
	{
		$select = $this->select()
				->order(array('position', 'name'))
				->where('searchable = ?', System_Model_Attribute::SEARCHABLE);
		
		return $this->fetchAll($select);
	}
	
	public function findAttributeByName($value, $id = null)
	{
		return $this->_findByParam('name', $value, $id);
	}
	
	public function findAttributeByCode($value, $id = null)
	{
		return $this->_findByParam('code', $value, $id);
	}
	
	protected function _findByParam($paramName, $paramValue, $id)
	{
		$value = (string) $paramValue;
		
		$result = $this->fetchAll(
						$this->select()
							->where($paramName . ' = ?', $value)
					);
		
		if (empty($id) && ($result->count() != 0)) {
			return true;
		} else if ($result->count() != 0) {
			foreach ($result as $attribute) {
				if ($attribute['attribute_id'] != $id) {
					return true;
				}
			}
		}
		return false;
	}
	
	public function getAttributeNamesAsArray()
	{
		if (is_null($this->_collection)) {
			$data = Gp_Cache_Manager::load(self::ATTRIBUTE_NAMES_AS_ARRAY);
			if (!empty($data)) {
				return $data;
			} else {
				$this->_collection = $this->getCollection();
								
				$data = array();
				foreach ($this->_collection as $attribute) {
					$data[$attribute['attribute_id']] = $attribute['name'];
				}
				
				Gp_Cache_Manager::save(self::ATTRIBUTE_NAMES_AS_ARRAY, $data, array(self::CACHE_TAGS));
			}
		}		
		return $data;
	}
	
	public function getCodeOnAttributesMapping() {
		if (is_null($this->_collection)) {
			$data = Gp_Cache_Manager::load(self::CODE_ON_ATTRIBUTES_MAPPING);
			if (!empty($data)) {
				return $data;
			} else {
				$this->_collection = $this->getCollection();			
				
				$data = array();
				foreach ($this->_collection as $attribute) {
					$data[$attribute['code']] = $attribute['name'];
				}
				
				Gp_Cache_Manager::save(self::CODE_ON_ATTRIBUTES_MAPPING, $data, array(self::CACHE_TAGS));
			}
		}		
		return $data;
	}
	
	/**
	 * 
	 * Create mapping columns on attributes
	 */
	public function getAttributesMapping()
	{
		if (is_null($this->_collection)) {
			$data = Gp_Cache_Manager::load(self::ATTRIBUTES_MAPPING);
			if (!empty($data)) {
				return $data;
			} else {
				$this->_collection = $this->getCollection();
				
				$data = array();
				foreach ($this->_collection as $attribute) {
					$data[$attribute['attribute_id']] = array(
						'name' => $attribute['name'], 
						'code' => $attribute['code'],
						'type' => $attribute['type']
					);
				}
				
				Gp_Cache_Manager::save(self::ATTRIBUTES_MAPPING, $data, array(self::CACHE_TAGS));
			}
		}		
		return $data;
	}
}